package com.itheima.rpc.netty.codec;

import com.itheima.rpc.data.RpcRequest;
import com.itheima.rpc.util.ProtostuffUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @desc 二次解码，使用固定的请求响应对象
 * @author:ivan.liu
 */
@Slf4j
public class RpcRequestDecoder extends MessageToMessageDecoder<ByteBuf> {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        try {
            byte[] bytes = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(bytes);
            RpcRequest rpcRequest = ProtostuffUtil.deserialize(bytes, RpcRequest.class);
            list.add(rpcRequest);
        } catch (Exception e) {
            log.error("序列化解码出错，请检查请求格式，msg={}",e.getMessage());
            throw new RuntimeException(e);
        }
    }
}
